{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#  数据库连接 - PyMySQL 驱动"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "import pymysql\n",
    "\n",
    "\n",
    "# 打开数据库连接\n",
    "db = pymysql.connect(\"localhost\",\"root\",\"123456\",\"TESTDB\" )\n",
    " \n",
    "# 使用 cursor() 方法创建一个游标对象 cursor\n",
    "cursor = db.cursor()\n",
    " \n",
    "# 使用 execute() 方法执行 SQL，如果表存在则删除\n",
    "cursor.execute(\"DROP TABLE IF EXISTS EMPLOYEE\")\n",
    " \n",
    "# 使用预处理语句创建表\n",
    "sql = \"\"\"CREATE TABLE EMPLOYEE (\n",
    "         FIRST_NAME  CHAR(20) NOT NULL,\n",
    "         LAST_NAME  CHAR(20),\n",
    "         AGE INT,  \n",
    "         SEX CHAR(1),\n",
    "         INCOME FLOAT )\"\"\"\n",
    " \n",
    "cursor.execute(sql)\n",
    " \n",
    "# 关闭数据库连接\n",
    "db.close()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [],
   "source": [
    "import pymysql\n",
    " \n",
    "# 打开数据库连接\n",
    "db = pymysql.connect(\"localhost\",\"root\",\"123456\",\"TESTDB\" )\n",
    " \n",
    "# 使用cursor()方法获取操作游标 \n",
    "cursor = db.cursor()\n",
    "\n",
    "\n",
    "# SQL 插入语句\n",
    "sql = \"\"\"INSERT INTO EMPLOYEE(FIRST_NAME,\n",
    "         LAST_NAME, AGE, SEX, INCOME)\n",
    "         VALUES ('Mac', 'Mohan', 20, 'M', 2000)\"\"\"\n",
    "try: \n",
    "   # 执行sql语句\n",
    "   cursor.execute(sql)\n",
    "   # 提交到数据库执行\n",
    "   db.commit()\n",
    "except:\n",
    "   # 如果发生错误则回滚\n",
    "   db.rollback()\n",
    " \n",
    " #关闭数据库连接\n",
    "db.close()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.1"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
